package controller

import (
	"github.com/gin-gonic/gin"
	"github.com/gogf/gf/util/gconv"
	"rock/customer/dto"
	"rock/customer/initParam"
	"rock/customer/middleware"
	"rock/customer/models"
	"rock/customer/modules/cacheMap"
	"rock/customer/public"
	service "rock/customer/service/master"
)

// @Summary 修改用户数据
// @Description
// @Tags 个人中心
// @ID /modifyuser
// @Accept  json
// @Produce  json
// @Param polygon body dto.UserInfo true "body"
// @Success 200 {object} middleware.Response{} "success"
// @Router /modifyuser [post]
func (w *PersonalCenterController) modifyUserDetail(router *gin.Context) {
	params := &dto.UserInfo{}
	if err := params.BindingParams(router); err != nil {
		middleware.ResponseError(router, middleware.PARMAS_ERROR_CODE, err)
		return
	}
	err := public.CheckTelPhone(params.Mobile)
	if err != nil {
		middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
		return
	}
	err = public.CheckEmail(params.Email)
	if err != nil {
		middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
		return
	}
	params.Name = public.Utf8mb4Filtration(params.Name)
	params.RealName = public.Utf8mb4Filtration(params.RealName)
	params.Company = public.Utf8mb4Filtration(params.Company)
	modifyParam := map[string]interface{}{
		"nickname":  params.Name,
		"avatar":    params.Avatar,
		"realname":  params.RealName,
		"mobile":    params.Mobile,
		"email":     params.Email,
		"co":        params.Company,
		"autograph": params.Job,
		"remark":    params.Remark,
	}
	if len(params.Introduce) > 0 {
		modifyParam["introduce"] = params.Introduce
	}
	if len(params.GoodAt) > 0 {
		modifyParam["field_id"] = params.GoodAt
	}
	if len(params.Address) > 0 {
		modifyParam["address"] = params.Address
	}
	if params.WorkYear != 0 {
		modifyParam["work_years"] = params.WorkYear
	}
	_, err = userService.UserByUserId(router, InstanceDB, params.UserId)
	if err != nil {
		dealRequestError(router, err)
		return
	}
	err = userService.UpdateUser(router, InstanceDB, params.UserId, modifyParam)
	if err != nil {
		middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
		return
	}
	middleware.ResponseSuccess(router, gin.H{"msg": initParam.DealSuccessText})
}

// @Summary 主页
// @Description 传参只需要传UserId
// @Tags 个人中心
// @ID /mypage
// @Accept json
// @Produce json
// @Param polygon body dto.User true "body"
// @Success 200 {object} middleware.Response{data=dto.UserDetail} "success"
// @Router /mypage [post]
func (w *PersonalCenterController) myPage(router *gin.Context) {
	params := &dto.User{}
	if err := params.BindingParams(router); err != nil {
		middleware.ResponseError(router, middleware.PARMAS_ERROR_CODE, err)
		return
	}
	//
	csUser, err := customerServiceService.CsUser(router, InstanceDB, gconv.Int(params.UserId))
	if err != nil {
		dealRequestError(router, err)
		return
	}
	count, err := serviceService.AchievementNum(router, BusinessDB, params.UserId)
	if err != nil {
		dealRequestError(router, err)
		return
	}
	csUser.AchievementNum = count
	responseData := csUser
	middleware.ResponseSuccess(router, responseData)
}

// @Summary 我的成就
// @Description 传参只需要传UserId
// @Tags 个人中心
// @ID /achievementlist
// @Accept json
// @Produce json
// @Param polygon body dto.User true "body"
// @Success 200 {object} middleware.Response{data=dto.IntegralList} "success"
// @Router /achievementlist [post]
func (w *PersonalCenterController) achievementList(router *gin.Context) {
	params := &dto.User{}
	if err := params.BindingParams(router); err != nil {
		middleware.ResponseError(router, middleware.PARMAS_ERROR_CODE, err)
		return
	}
	achievementList, count, err := serviceService.AchievementList(router, BusinessDB, params.UserId, params.PageNum, params.PageSize)
	if err != nil {
		dealRequestError(router, err)
		return
	}
	returnMsg := make(map[string][]dto.Integral, 0)
	for _, v := range achievementList {
		dateStr := v.CreatedAt.Format(initParam.TimeFormatYearDay)
		if len(returnMsg[dateStr]) == 0 {
			returnMsg[dateStr] = make([]dto.Integral, 0)
			returnMsg[dateStr] = append(returnMsg[dateStr], v)
		} else {
			returnMsg[dateStr] = append(returnMsg[dateStr], v)
		}
	}
	responseData := dto.IntegralList{
		Page: dto.Page{
			PageNum:  params.PageNum,
			PageSize: params.PageSize,
			Total:    count,
		},
		Integral: returnMsg,
	}
	middleware.ResponseSuccess(router, responseData)
}

// @Summary 更改用户在线状态
// @Description 传入 userId 和 isOnline
// @Tags 个人中心
// @ID /modifyuseronline
// @Accept  json
// @Produce  json
// @Param polygon body dto.User true "body"
// @Success 200 {object} middleware.Response{} "success"
// @Router /modifyuseronline [post]
func (w *PersonalCenterController) modifyUserOnline(router *gin.Context) {
	params := &dto.User{}
	if err := params.BindingParams(router); err != nil {
		middleware.ResponseError(router, middleware.PARMAS_ERROR_CODE, err)
		return
	}
	if params.IsCustomerClient == 1 {
		cacheMap.CustomerOnline.Set(params.UserId, params.IsOnline)
		//
		groupC, err := groupService.GroupC(router, service.BusinessDB, params.UserId, "0")
		if err != nil {
			if err.Error() != initParam.DataIsNotExist {
				middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
				return
			}
			groupC = models.WkbGroup{}
		}
		if groupC.GroupID != "" {
			report(groupC.GroupID, params.IsOnline)
		}
	} else {
		//
		err := customerServiceService.UpdateCsUserOnline(router, BusinessDB, params.UserId, params.IsOnline)
		if err != nil {
			middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
			return
		}
		if params.IsOnline == 1 && cacheMap.ToBeAllocated.Size() > 0 {
			// TODO 需要客服接入群聊
			//imCustomerServiceGroup, err := customerServiceService.CsUser(router, BusinessDB, gconv.Int(params.UserId))
			//if err != nil {
			//	middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
			//	return
			//}
			//for _, v := range imCustomerServiceGroup {
			//	toBeAllocatedCache := cacheMap.ToBeAllocated.Get(v.GroupId)
			//	if toBeAllocatedCache != nil {
			//		toBeAllocated := toBeAllocatedCache.([]models.WkbGroup)
			//		for _, vv := range toBeAllocated {
			//			//引入客服 为客户服务
			//			err = joinGroup(router, 2, 1, dto.UserDetail{
			//				UserId:   v.UserId,
			//				Nickname: v.Nickname,
			//				Avatar:   v.Avatar,
			//				IsManage: v.IsManage,
			//			}, models.WkbGroup{
			//				GroupID: vv.GroupID,
			//				Name:    vv.Name,
			//			}, v.GroupId)
			//			if err != nil {
			//				middleware.ResponseError(router, middleware.PARMAS_ERROR_CODE, err)
			//				return
			//			}
			//			//
			//			updateRedis(router, vv.GroupID)
			//		}
			//		cacheMap.ToBeAllocated.Remove(v.GroupId)
			//	}
			//}
		}
	}
	middleware.ResponseSuccess(router, gin.H{"msg": initParam.DealSuccessText})
}
